import { Request, Response } from 'express';
import bcrypt from 'bcryptjs';
import User from '../models/User';
import generateToken from '../utils/generateToken';
import { AuthRequest } from '../types';

export const registerUser = async (req: Request, res: Response) => {
    const { username, email, password } = req.body;
    try {
        if (!username || !email || !password) { return res.status(400).json({ message: 'Please add all fields' }); }
        const userExists = await User.findOne({ email });
        if (userExists) { return res.status(400).json({ message: 'User already exists' }); }
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);
        const user = await User.create({ username, email, password: hashedPassword });
        if (user) {
            res.status(201).json({
                _id: user._id,
                username: user.username,
                email: user.email,
                role: user.role,
                // 【修正】使用 (user as any) 解决 _id 的 'unknown' 类型问题
                token: generateToken((user as any)._id.toString())
            });
        } else {
            res.status(400).json({ message: 'Invalid user data' });
        }
    } catch (error) { res.status(500).json({ message: 'Server Error' }); }
};

export const loginUser = async (req: Request, res: Response) => {
    const { email, password } = req.body;
    try {
        const user = await User.findOne({ email });
        // 【修正】再次确认 user.password 存在，以匹配 bcrypt 的类型要求
        if (user && user.password && (await bcrypt.compare(password, user.password))) {
            res.json({
                _id: user._id,
                username: user.username,
                email: user.email,
                role: user.role,
                // 【修正】使用 (user as any) 解决 _id 的 'unknown' 类型问题
                token: generateToken((user as any)._id.toString())
            });
        } else {
            res.status(401).json({ message: 'Invalid email or password' });
        }
    } catch (error) { res.status(500).json({ message: 'Server Error' }); }
};

export const getUserProfile = async (req: AuthRequest, res: Response) => {
    const user = req.user;
    if (user) {
        // 使用 populate 填充 user 文档中的 teams 字段
        const userProfile = await user.populate('teams', 'name');
        res.json(userProfile);
    } else {
        res.status(404).json({ message: 'User not found' });
    }
};